package cn.chenxiejia;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @version : V1.0
 * @program: maven
 * @ClassName: Gbf2
 * @Description: cyclicBarrier各个线程运行至某个状态，随后一起执行
 * @Author: chenxiejia
 * @Date: 2022/2/17 20:45
 */
public class Gbf2 {
    public static volatile boolean flag = true;

    public static void main(String[] args) throws InterruptedException {
        int N = 10;

        CyclicBarrier cb = new CyclicBarrier(N, new Thread3());
        while (flag) {
            flag = false;
            for (int i = 1; i < 11; i++) {
                new Thread(new Thread2(i, cb, flag)).start();
            }
            TimeUnit.SECONDS.sleep(1);
            flag = true;
        }
    }
}

class Thread2 implements Runnable {
    public int N;
    public CyclicBarrier cb;
    public boolean flag;

    public Thread2(int N, CyclicBarrier cb, boolean flag) {
        this.N = N;
        this.cb = cb;
        this.flag = flag;
    }

    @Override
    public void run() {
        flag = false;
        Random rand = new Random();
        int a = rand.nextInt(1, 10);
        try {
            TimeUnit.SECONDS.sleep(a);
            System.out.println("士兵" + N + "已到达！");
            cb.await();
            System.out.println("一起出发");

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

class Thread3 implements Runnable {
    @Override
    public void run() {
        System.out.println("出发");
    }
}
